package com.zhongcw.tool.kuaichuan.client;

import com.zhongcw.tool.kuaichuan.server.Server_2;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * 客户端
 */
public class Client_2 extends Socket {

    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 2013;

    private Socket client;
    private FileInputStream fis;
    private DataOutputStream dos;

    public Client_2() {
        try {
            try {
                System.out.println("请求连接。。。");
                client = new Socket(SERVER_IP, SERVER_PORT);

                System.out.println("连接成功。。。");
                //向服务端传送文件
//                File file = new File("D:\\tempfile\\Client_spring-tool-suite-3.9.0.RELEASE-e4.7.0-win32-x86_64(1).zip");
                File file = new File("E:\\安装包\\oracle 11g\\win64_11gR2_database_1of2.zip");
                fis = new FileInputStream(file);
                dos = new DataOutputStream(client.getOutputStream());

                //文件名和长度
                dos.writeUTF(file.getName());
                dos.writeLong(file.length());
                dos.flush();

                //传输文件 100M/次
                byte[] sendBytes = new byte[(int)Math.pow(1024D,2D)*100];
                int length = 0;
                int i=0;
                while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
                    dos.write(sendBytes, 0, length);
                    i++;
                    dos.flush();
                }

                System.out.println("该文件分为 "+i+" 发送");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    fis.close();
                }
                if (dos != null) {
                    dos.close();
                }
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

//        new Thread(new Runnable() {
//            public void run() {
//                try {
//                    new Server_2();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
////        }).start();
//        });

        new Client_2();
    }
}